import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { User } from '../../models/User';
import { Department } from '../../models/Department';
import { UserService } from '../../service/UserService';

@Component({
  templateUrl: './userAdd.html',
  styleUrls: ['./userAdd.css']
})
export class  UserAddComponent implements OnInit, AfterViewChecked {

  messages = {
    realName: '',
    userName: '',
    phone: '',
    email: ''
  };
  departments: Department[];
  user: User;


  constructor(
    private dialogRef: MatDialogRef<UserAddComponent>,
    private userService: UserService,
    @Inject(MAT_DIALOG_DATA) public data: {user: User, departments: Department[]}
   ) {
    this.user = data.user || new User();
    this.departments = data.departments;

  }

  @ViewChild('userForm')
  userForm: NgForm;

  ngAfterViewChecked() {
    if (this.userForm) {
      this.userForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {

  }

  onSubmit() {
    this.checkValidate(true);
    if (this.userForm.invalid) {
      // 触发mat的error
      this.userForm.onSubmit(null);
      return false;
    }
    if (this.user.id !== undefined) {
      this.userService.update(this.user).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    } else {
      this.user.mima = '123456zxx';
      this.userService.register(this.user).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    }

  }

  checkValidate(isSubmit?: boolean) {
    const form = this.userForm;

    for (const field in UserAddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = UserAddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }

  static ErrorMessages = {
    realName: {
      required: '姓名不能为空'
    },
    userName: {
      pattern: '以字母开头，由4-20个字母、数字和"_"组成',
      required: '用户名不能为空'
    },
    phone: {
      pattern: '手机号格式不正确',
      required: '手机号不能为空'
    },
    email: {
      pattern: '邮箱格式不正确',
      required: '邮箱不能为空'
    }
  };
}
